package com.qf.business.user.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.business.user.core.dao.SysUserDao;
import com.qf.business.user.core.service.SysUserRoleService;
import com.qf.business.user.core.service.SysUserService;
import com.qf.data.user.dto.SysUserPowersDto;
import com.qf.data.user.entity.SysUser;
import com.qf.data.user.entity.SysUserRole;
import com.qf.data.user.vo.input.SysSetUserRoleInput;
import com.qf.data.user.vo.input.SysUserSearchInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统用户表(SysUser)表服务实现类
 *
 * @author makejava
 * @since 2022-08-31 14:11:27
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements SysUserService {

    @Autowired
    private SysUserRoleService userRoleService;

    /**
     * 设置用户的角色信息
     * @param userRoleInput
     * @return
     */
    @Override
    @Transactional
    public int updateRoles(SysSetUserRoleInput userRoleInput) {
        //根据用户删除所有的关联角色
        userRoleService.deleteUserRoleByUid(userRoleInput.getUid());

        if(CollectionUtils.isEmpty(userRoleInput.getRids())){
            return 0;
        }

        //循环转换
        List<SysUserRole> userRoles = userRoleInput.getRids().stream()
                .map(rid -> new SysUserRole().setUid(userRoleInput.getUid()).setRid(rid))
                .collect(Collectors.toList());
        //批量保存
        userRoleService.saveBatch(userRoles);
        return 1;
    }

    /**
     * 根据用户名查询用户信息以及权限信息
     * @param username
     * @return
     */
    @Override
    public SysUserPowersDto queryUserByUn(String username) {
        return getBaseMapper().queryUserByUn(username);
    }

    /**
     * 根据条件 搜索用户列表
     * @param searchInput
     * @return
     */
    @Override
    public List<SysUser> search(SysUserSearchInput searchInput) {
        return getBaseMapper().search(searchInput);
    }
}

